
#include <stdio.h>
#include "wm_hal.h"
#include "Ff.h"

SD_HandleTypeDef hsd;

#define LEN 1000

void Error_Handler(void);
static void sd_init(void);
static uint8_t wb[LEN] = {0};
static uint8_t rb[LEN] = {0};
static uint8_t work[FF_MAX_SS];

int main(void)
{
	int i = 0;
	FRESULT res;
	char path[32];
	FATFS fs;
	FIL fp;
	uint32_t n = 0;
	
	SystemClock_Config(CPU_CLK_240M);
	printf("enter main\r\n");
	
	sd_init();
	memset(wb, 0, LEN);
	memset(rb, 0, LEN);
	for (i = 0; i < LEN; i++)
	{
		wb[i] = i % 256;
	}
	do{
		res = f_mount(&fs, "0:", 1);
		if (res == FR_NO_FILESYSTEM)
		{
			printf("sd card no fatfs system, do format...");
			res = f_mkfs("0:", 0, work, sizeof(work));
			if (res != FR_OK)
			{
				printf("sd card format failed, res = %d\r\n", res);
			}
			printf("sd card format success.\r\n");
			res = f_mount(NULL, "0:", 1);
			res = f_mount(&fs, "0:", 1);
			if (res != FR_OK)
			{
				printf("mount failed. res = %d\r\n", res);
			}
			printf("mount success.\r\n");
		}
		else if (res != FR_OK)
		{
			printf("mount failed. res = %d\r\n", res);
		}
		else
		{
			printf("mount success.\r\n");
		}
	}while(res != FR_OK);
	
	printf("begin write demo.dat\r\n");
	sprintf(path, "0:demo.dat");
	
	res = f_open(&fp, path, (FA_CREATE_ALWAYS | FA_WRITE));
	if (res != FR_OK)
	{
		printf("when write, open file failed. res = %d\r\n", res);
		Error_Handler();
	}
	res = f_write(&fp, wb, LEN, &n);
	if (res != FR_OK)
	{
		printf("write failed. res = %d\r\n", res);
		Error_Handler();
	}
	res = f_close(&fp);
	if (res != FR_OK)
	{
		printf("write close file failed. res = %d\r\n", res);
		Error_Handler();
	}
	printf("write demo.dat finish\r\n");

	printf("begin read demo.dat\r\n");
	res = f_open(&fp, path, (FA_OPEN_EXISTING | FA_READ));
	if (res != FR_OK)
	{
		printf("when read, open file failed. res = %d\r\n", res);
	}
	memset(rb, 0, LEN);
	res = f_read(&fp, rb, LEN, &n);
	if (res != FR_OK)
	{
		printf("read failed. res = %d\r\n", res);
		Error_Handler();
	}
	res = f_close(&fp);
	if (res != FR_OK)
	{
		printf("read close file failed. res = %d\r\n", res);
	}
	printf("read demo.dat finish\r\n");
	if (memcmp(wb, rb, LEN))
	{
		printf("file write then read failed.\r\n");
		Error_Handler();
	}
	else
	{
		printf("file write then read success.\r\n");
	}

	while (1)
	{
		printf(".");
		HAL_Delay(1000);
	}
}

static void sd_init(void)
{
	hsd.Instance = SD;
	hsd.Init.BusWide = SD_BUS_WIDE_4B;
	hsd.Init.ClockMode = SD_CLOCK_MODE_HIGH_SPEED;
	hsd.Init.ClockDiv = SD_CLOCK_DIV_1_6;
	// fatfs里会调用HAL_SD_Init(),所以这里不用调用
#if 0
	if (HAL_SD_Init(&hsd) != HAL_OK)
	{
		printf("sdio init failed\r\n");
		Error_Handler();
	}
#endif
}

void Error_Handler(void)
{
	while (1)
	{
	}
}

void assert_failed(uint8_t *file, uint32_t line)
{
	printf("Wrong parameters value: file %s on line %d\r\n", file, line);
}